#!/bin/sh
### BEGIN INIT INFO
# Provides:          haproxy
# Required-Start:    $local_fs $network $remote_fs $syslog $named
# Required-Stop:     $local_fs $remote_fs $syslog $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: fast and reliable load balancing reverse proxy
# Description:       This file should be used to start and stop haproxy.
### END INIT INFO

# Author: Arnaud Cornet <acornet@debian.org>

PATH=/sbin:/usr/sbin:/bin:/usr/bin
BASENAME=haproxy-lkl
HAPROXY_LKL_DIR=/usr/local/$BASENAME
HAPROXY=${HAPROXY_LKL_DIR}/sbin/haproxy
HAPROXY_LKL=${HAPROXY_LKL_DIR}/sbin/$BASENAME

PIDFILE=/var/run/${BASENAME}.pid
CONFIG=${HAPROXY_LKL_DIR}/etc/haproxy.cfg

RETVAL=0

test -x $HAPROXY || exit 0
test -x $HAPROXY_LKL || exit 0

. /lib/lsb/init-functions

do_start() {
	if get_status; then
		return 1
	fi

	start-stop-daemon --quiet --oknodo --start --pidfile "$PIDFILE" \
		--exec $HAPROXY_LKL -- -p "$PIDFILE" || return 2
	return 0
}

do_stop() {
	# clear iptables rules
	$HAPROXY_LKL -c >/dev/null 2>&1

	if [ ! -f $PIDFILE ] ; then
		# This is a success according to LSB
		return 3
	fi

	ret=0
	start-stop-daemon --quiet --oknodo --stop \
		--retry 5 --pidfile "$PIDFILE" --exec $HAPROXY || ret=$?

	[ $ret -eq 0 ] && rm -f $PIDFILE

	return $ret
}

get_status() {
	if [ ! -f $PIDFILE ] ; then
		# program not running
		return 3
	fi

	if ! ps --no-headers p "$(cat $PIDFILE)" | grep -q 'haproxy'; then
		# program running, bogus pidfile
		return 1
	fi

	return 0
}

case "$1" in
	start)
		log_daemon_msg "Starting haproxy" "${BASENAME}"
		do_start
		RETVAL=$?
		case "$RETVAL" in
		0)
			log_end_msg 0
			;;
		1)
			log_end_msg 1
			echo "pid file '$PIDFILE' found, and ${BASENAME} already running."
			;;
		2)
			log_end_msg 1
			;;
		esac
		;;
	stop)
		log_daemon_msg "Stopping haproxy" "${BASENAME}"
		do_stop
		RETVAL=$?
		case "$RETVAL" in
		0|1)
			log_end_msg 0
			;;
		2)
			log_end_msg 1
			;;
		3)
			log_end_msg 1
			echo "Can't find pid file '$PIDFILE'."
			;;
		esac
		;;
	restart)
		log_daemon_msg "Restarting haproxy" "${BASENAME}"
		do_stop
		do_start
		RETVAL=$?
		case "$RETVAL" in
		0)
			log_end_msg 0
			;;
		1)
			log_end_msg 1
			;;
		2)
			log_end_msg 1
			;;
		esac
		;;
	status)
		get_status
		RETVAL=$?
		case "$RETVAL" in
		0)
			echo "${BASENAME} is running."
			;;
		1)
			echo "${BASENAME} dead, but $PIDFILE exists."
			;;
		*)
			echo "${BASENAME} not running."
			;;
		esac
		;;
	*)
		echo "Usage: /etc/init.d/${BASENAME} {start|stop|restart|status}"
		RETVAL=255
		;;
esac

exit $RETVAL
